pub mod add;
pub mod copy;
pub mod delete;
pub mod edit;
pub mod delay;
pub mod list;
mod id;
mod complete;
mod pending;
mod clear;

use crate::commands::add::Add;
use crate::commands::clear::Clear;
use crate::commands::complete::Complete;
use crate::commands::delay::Delay;
use crate::commands::delete::Delete;
use crate::commands::edit::Edit;
use crate::commands::id::Id;
use crate::commands::list::List;
use crate::commands::pending::Pending;
use crate::error::TodoError;
use anyhow::Result;
use chrono::NaiveDate;
use clap::{ColorChoice, Parser};

pub type CP = copy::Copy;

#[derive(Parser, Debug)]
#[command(
    name = "todo",
    version = "1.0",
    author = "Silwings<silwings@163.com>",
    color = ColorChoice::Auto,
    about = "To-do CLI - 高效的命令行待办事项管理工具\n\n一个简洁的命令行工具，帮助你轻松管理待办事项。\n支持添加、编辑、删除、延期、查询、标记完成等操作。\n无论是日常任务管理，还是临时任务处理，都能高效便捷地完成。\n使用 `todo --help` 查看所有命令和选项。"
)]
pub struct Opts {
    #[clap(subcommand)]
    pub subcmd: SubCommand,
}

#[derive(Parser, Debug)]
pub enum SubCommand {
    /// 添加新的待办
    Add(Add),

    /// 复制现有的待办,并指定日期为今天
    Cp(CP),

    /// 删除待办
    Delete(Delete),

    /// 编辑待办
    Edit(Edit),

    /// 查询待办列表
    List(List),

    /// 将待办延期一天
    Delay(Delay),

    /// 查看待办
    Id(Id),

    /// 将待办标记为完成
    C(Complete),

    /// 将待办标记为未完成
    P(Pending),

    /// 删除全部待办,并重置ID
    Clear(Clear),
}

pub fn parse_date(date_str: &str) -> Result<NaiveDate, TodoError> {
    let formats = [
        "%Y-%m-%d",      // 2024-01-01
        "%Y%m%d",        // 20240101
        "%y%m%d",        // 240101
        "%Y年%m月%d日", // 2024年1月1日
        "%Y年%m月%d号", // 2024年1月1号
        "%Y年%m月%d", // 2024年1月1
    ];

    // Try parsing with each format until one succeeds
    for format in &formats {
        if let Ok(date) = NaiveDate::parse_from_str(date_str, format) {
            return Ok(date);
        }
    }

    // If none of the formats match, return an error
    Err(TodoError::DateFormatError())
}
